<template>
  <section class="demo-section">
    <div class="demo-header">
      <h2 class="demo-title">6. defineOptions 组件选项定义 (Vue 3.3+)</h2>
      <p class="demo-description">
        defineOptions 是 Vue 3.3+ 引入的编译器宏，允许在 &lt;script setup&gt;
        中直接定义组件选项。 它解决了在组合式 API
        中无法直接设置组件名称、继承属性等选项的问题，提供了更简洁的语法。
      </p>
    </div>

    <div class="demo-content">
      <!-- 组件名称和继承属性演示 -->
      <div class="demo-card">
        <h3 class="card-title">📝 组件名称与继承属性</h3>
        <div class="demo-area">
          <div class="info-panel">
            <div class="info-item">
              <span class="info-label">组件名称:</span>
              <span class="info-value">{{ componentInfo.name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">继承属性:</span>
              <span class="info-value">{{
                componentInfo.inheritAttrs ? "启用" : "禁用"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">组件实例:</span>
              <span class="info-value">{{ componentInfo.instance }}</span>
            </div>
          </div>

          <div class="example-container">
            <h4>演示组件实例:</h4>
            <CustomCard
              title="测试卡片"
              :data-custom="customData"
              class="demo-card-instance"
              @click="handleCardClick"
            >
              <p>这是一个使用 defineOptions 定义的自定义组件</p>
              <p>点击查看继承属性的效果</p>
            </CustomCard>
          </div>
        </div>
      </div>

      <!-- 自定义指令和插件演示 -->
      <div class="demo-card">
        <h3 class="card-title">🔌 自定义指令与插件</h3>
        <div class="demo-area">
          <div class="directive-demo">
            <h4>自定义指令演示:</h4>
            <div class="directive-examples">
              <div v-highlight="highlightColor" class="highlight-box">
                <p>这个元素使用了自定义的 v-highlight 指令</p>
                <p>当前高亮颜色: {{ highlightColor }}</p>
              </div>

              <div class="controls">
                <label>选择高亮颜色:</label>
                <select v-model="highlightColor" class="color-select">
                  <option value="yellow">黄色</option>
                  <option value="lightblue">浅蓝色</option>
                  <option value="lightgreen">浅绿色</option>
                  <option value="lightpink">浅粉色</option>
                </select>
              </div>

              <div v-focus="shouldFocus" class="focus-demo">
                <input
                  ref="focusInput"
                  type="text"
                  placeholder="这个输入框会自动获得焦点"
                  class="demo-input"
                />
                <button @click="shouldFocus = !shouldFocus" class="btn btn-primary">
                  {{ shouldFocus ? "取消焦点" : "设置焦点" }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 生命周期钩子演示 -->
      <div class="demo-card">
        <h3 class="card-title">🔄 组件生命周期追踪</h3>
        <div class="demo-area">
          <div class="lifecycle-tracker">
            <h4>生命周期事件日志:</h4>
            <div class="lifecycle-log">
              <div
                v-for="(log, index) in lifecycleLogs"
                :key="index"
                class="log-item"
                :class="log.type"
              >
                <span class="log-time">{{ log.time }}</span>
                <span class="log-event">{{ log.event }}</span>
                <span class="log-message">{{ log.message }}</span>
              </div>
            </div>

            <div class="lifecycle-controls">
              <button @click="clearLogs" class="btn btn-secondary">清空日志</button>
              <button @click="triggerUpdate" class="btn btn-primary">触发更新</button>
              <button @click="toggleComponent" class="btn btn-warning">
                {{ showDynamicComponent ? "销毁组件" : "创建组件" }}
              </button>
            </div>

            <div v-if="showDynamicComponent" class="dynamic-component-area">
              <DynamicTestComponent
                :update-counter="updateCounter"
                @lifecycle="handleLifecycleEvent"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 代码对比演示 -->
      <div class="demo-card">
        <h3 class="card-title">📊 传统方式 vs defineOptions</h3>
        <div class="comparison">
          <div class="comparison-column">
            <h4>❌ 传统方式 (Vue 3.2)</h4>
            <div class="code-example">
              <pre><code>&lt;script&gt;
export default {
  name: 'MyComponent',
  inheritAttrs: false,
  directives: {
    highlight: {
      mounted(el, binding) {
        el.style.backgroundColor = binding.value
      }
    }
  },
  setup() {
    // 组合式 API 逻辑
    return {}
  }
}
&lt;/script&gt;</code></pre>
            </div>
          </div>

          <div class="comparison-column">
            <h4>✅ defineOptions (Vue 3.3+)</h4>
            <div class="code-example">
              <pre><code>&lt;script setup&gt;
defineOptions({
  name: 'MyComponent',
  inheritAttrs: false,
  directives: {
    highlight: {
      mounted(el, binding) {
        el.style.backgroundColor = binding.value
      }
    }
  }
})

// 直接编写组合式 API 逻辑
&lt;/script&gt;</code></pre>
            </div>
          </div>
        </div>

        <div class="benefits">
          <h4>🚀 优势对比:</h4>
          <ul>
            <li>
              ✅ <strong>语法统一</strong> - 在 &lt;script setup&gt; 中直接定义所有选项
            </li>
            <li>✅ <strong>类型安全</strong> - 更好的 TypeScript 支持和类型推导</li>
            <li>✅ <strong>代码简洁</strong> - 无需分离 setup 和 options</li>
            <li>✅ <strong>开发体验</strong> - 减少样板代码，提升开发效率</li>
          </ul>
        </div>
      </div>

      <!-- 实际应用场景 -->
      <div class="demo-card">
        <h3 class="card-title">💡 实际应用场景</h3>
        <div class="use-cases">
          <div class="use-case">
            <h4>🏷️ 组件库开发</h4>
            <p>为组件库中的组件设置统一的命名规范和属性继承策略</p>
            <div class="code-snippet">
              <pre><code>defineOptions({
  name: 'ElButton',
  inheritAttrs: false
})</code></pre>
            </div>
          </div>

          <div class="use-case">
            <h4>🎨 自定义指令</h4>
            <p>在组件中定义和使用局部自定义指令</p>
            <div class="code-snippet">
              <pre><code>defineOptions({
  directives: {
    tooltip: tooltipDirective,
    clickOutside: clickOutsideDirective
  }
})</code></pre>
            </div>
          </div>

          <div class="use-case">
            <h4>🔧 开发工具集成</h4>
            <p>为 Vue DevTools 提供更好的组件识别和调试信息</p>
            <div class="code-snippet">
              <pre><code>defineOptions({
  name: 'UserProfile',
  __debugName: 'UserProfile-v2.1'
})</code></pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  onMounted,
  onUpdated,
  onUnmounted,
  getCurrentInstance,
} from "vue";

// 使用 defineOptions 定义组件选项
defineOptions({
  name: "DefineOptionsDemo",
  inheritAttrs: true,
  directives: {
    highlight: {
      mounted(el: HTMLElement, binding: any) {
        el.style.backgroundColor = binding.value;
        el.style.transition = "background-color 0.3s ease";
      },
      updated(el: HTMLElement, binding: any) {
        el.style.backgroundColor = binding.value;
      },
    },
    focus: {
      mounted(el: HTMLElement, binding: any) {
        if (binding.value) {
          el.querySelector("input")?.focus();
        }
      },
      updated(el: HTMLElement, binding: any) {
        if (binding.value) {
          el.querySelector("input")?.focus();
        } else {
          el.querySelector("input")?.blur();
        }
      },
    },
  },
});

// 组件数据
const highlightColor = ref("yellow");
const shouldFocus = ref(true);
const customData = ref("custom-attribute-value");
const updateCounter = ref(0);
const showDynamicComponent = ref(false);

// 组件信息
const componentInfo = reactive({
  name: "DefineOptionsDemo",
  inheritAttrs: true,
  instance: "Vue 3.3+ defineOptions",
});

// 生命周期日志
interface LifecycleLog {
  time: string;
  event: string;
  message: string;
  type: "info" | "success" | "warning";
}

const lifecycleLogs = ref<LifecycleLog[]>([]);

// 添加生命周期日志
const addLifecycleLog = (
  event: string,
  message: string,
  type: "info" | "success" | "warning" = "info"
) => {
  lifecycleLogs.value.push({
    time: new Date().toLocaleTimeString(),
    event,
    message,
    type,
  });
};

// 事件处理
const handleCardClick = () => {
  addLifecycleLog("用户交互", "自定义卡片被点击", "info");
};

const clearLogs = () => {
  lifecycleLogs.value = [];
};

const triggerUpdate = () => {
  updateCounter.value++;
  addLifecycleLog("手动触发", `组件更新 #${updateCounter.value}`, "warning");
};

const toggleComponent = () => {
  showDynamicComponent.value = !showDynamicComponent.value;
  addLifecycleLog(
    "组件切换",
    showDynamicComponent.value ? "动态组件已创建" : "动态组件已销毁",
    showDynamicComponent.value ? "success" : "warning"
  );
};

const handleLifecycleEvent = (data: { event: string; message: string }) => {
  addLifecycleLog(data.event, data.message, "success");
};

// 生命周期钩子
onMounted(() => {
  addLifecycleLog("onMounted", "DefineOptionsDemo 组件已挂载", "success");
});

onUpdated(() => {
  addLifecycleLog("onUpdated", "DefineOptionsDemo 组件已更新", "info");
});

onUnmounted(() => {
  addLifecycleLog("onUnmounted", "DefineOptionsDemo 组件已销毁", "warning");
});
</script>

<!-- 自定义组件定义 -->
<script lang="tsx">
import { defineComponent } from "vue";

// 自定义卡片组件
export const CustomCard = defineComponent({
  props: {
    title: String,
    dataCustom: String,
  },
  setup(props, { attrs, slots }) {
    return () => (
      <div class="custom-card" {...attrs}>
        <div class="card-header">
          <h5>{props.title}</h5>
          <span class="card-attrs">继承属性: {JSON.stringify(attrs)}</span>
        </div>
        <div class="card-content">{slots.default?.()}</div>
      </div>
    );
  },
});

// 动态测试组件
export const DynamicTestComponent = defineComponent({
  props: {
    updateCounter: Number,
  },
  emits: ["lifecycle"],
  setup(props, { emit }) {
    onMounted(() => {
      emit("lifecycle", { event: "onMounted", message: "动态组件已挂载" });
    });

    onUpdated(() => {
      emit("lifecycle", {
        event: "onUpdated",
        message: `动态组件已更新 (${props.updateCounter})`,
      });
    });

    onUnmounted(() => {
      emit("lifecycle", { event: "onUnmounted", message: "动态组件已销毁" });
    });

    return () => (
      <div class="dynamic-component">
        <h5>动态测试组件</h5>
        <p>更新计数: {props.updateCounter}</p>
        <p>这个组件用于演示生命周期事件</p>
      </div>
    );
  },
});
</script>

<style scoped>
.demo-section {
  background: white;
  margin-bottom: 3rem;
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.05);
}

.demo-header {
  margin-bottom: 2rem;
}

.demo-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 1rem;
}

.demo-description {
  font-size: 1rem;
  color: #64748b;
  line-height: 1.7;
  background: #f8fafc;
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.demo-content {
  display: grid;
  gap: 2rem;
}

.demo-card {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 1.5rem;
  background: #fafbfc;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.demo-area {
  display: grid;
  gap: 1.5rem;
}

.info-panel {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f1f5f9;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 600;
  color: #374151;
}

.info-value {
  color: #667eea;
  font-weight: 500;
  padding: 0.25rem 0.75rem;
  background: #f0f4ff;
  border-radius: 6px;
}

.example-container {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.example-container h4 {
  margin: 0 0 1rem 0;
  color: #374151;
}

.custom-card {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 1.5rem;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.custom-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.card-header {
  margin-bottom: 1rem;
}

.card-header h5 {
  margin: 0 0 0.5rem 0;
  font-size: 1.25rem;
}

.card-attrs {
  font-size: 0.8rem;
  opacity: 0.8;
  background: rgba(255, 255, 255, 0.2);
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.card-content p {
  margin: 0.5rem 0;
  line-height: 1.5;
}

.directive-demo {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.directive-demo h4 {
  margin: 0 0 1rem 0;
  color: #374151;
}

.directive-examples {
  display: grid;
  gap: 1.5rem;
}

.highlight-box {
  padding: 1.5rem;
  border-radius: 8px;
  border: 2px dashed #e2e8f0;
  text-align: center;
  transition: all 0.3s ease;
}

.highlight-box p {
  margin: 0.5rem 0;
  color: #374151;
  font-weight: 500;
}

.controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: #f8fafc;
  border-radius: 8px;
}

.controls label {
  font-weight: 600;
  color: #374151;
}

.color-select {
  padding: 0.5rem;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 1rem;
}

.color-select:focus {
  outline: none;
  border-color: #667eea;
}

.focus-demo {
  display: flex;
  gap: 1rem;
  align-items: center;
  padding: 1rem;
  background: #f8fafc;
  border-radius: 8px;
}

.demo-input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.demo-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5a67d8;
  transform: translateY(-1px);
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

.lifecycle-tracker {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.lifecycle-tracker h4 {
  margin: 0 0 1rem 0;
  color: #374151;
}

.lifecycle-log {
  background: #1e293b;
  color: #e2e8f0;
  padding: 1rem;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 1rem;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 0.9rem;
}

.log-item {
  display: flex;
  gap: 1rem;
  padding: 0.5rem 0;
  border-bottom: 1px solid #374151;
}

.log-item:last-child {
  border-bottom: none;
}

.log-item.info {
  color: #93c5fd;
}

.log-item.success {
  color: #86efac;
}

.log-item.warning {
  color: #fbbf24;
}

.log-time {
  color: #9ca3af;
  font-size: 0.8rem;
  min-width: 80px;
}

.log-event {
  font-weight: 600;
  min-width: 120px;
}

.log-message {
  flex: 1;
}

.lifecycle-controls {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.dynamic-component-area {
  margin-top: 1rem;
}

.dynamic-component {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
  padding: 1.5rem;
  border-radius: 8px;
}

.dynamic-component h5 {
  margin: 0 0 0.5rem 0;
  font-size: 1.1rem;
}

.dynamic-component p {
  margin: 0.25rem 0;
  opacity: 0.9;
}

.comparison {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  margin-bottom: 2rem;
}

.comparison-column h4 {
  margin: 0 0 1rem 0;
  color: #374151;
}

.code-example {
  background: #1e293b;
  color: #e2e8f0;
  padding: 1rem;
  border-radius: 8px;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 0.9rem;
  overflow-x: auto;
}

.code-example pre {
  margin: 0;
  white-space: pre-wrap;
}

.benefits {
  background: #f0f9ff;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #0ea5e9;
}

.benefits h4 {
  margin: 0 0 1rem 0;
  color: #0c4a6e;
}

.benefits ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.benefits li {
  padding: 0.5rem 0;
  color: #0369a1;
  line-height: 1.5;
}

.use-cases {
  display: grid;
  gap: 1.5rem;
}

.use-case {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.use-case h4 {
  margin: 0 0 0.5rem 0;
  color: #374151;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.use-case > p {
  color: #64748b;
  margin-bottom: 1rem;
  line-height: 1.5;
}

.code-snippet {
  background: #f8fafc;
  padding: 1rem;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.code-snippet pre {
  margin: 0;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 0.85rem;
  color: #374151;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .comparison {
    grid-template-columns: 1fr;
  }

  .controls {
    flex-direction: column;
    align-items: stretch;
  }

  .focus-demo {
    flex-direction: column;
  }

  .lifecycle-controls {
    flex-direction: column;
  }

  .lifecycle-controls .btn {
    width: 100%;
  }
}
</style>
